package com.magnate.software.spring.cloud.ribbon.service;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCollapser;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * Class Desc
 *
 * @author WangYang
 * @version 1.0
 * @datetime 2017/2/21 10:53
 */
@Service("userService")
public class UserServiceImpl {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserServiceImpl.class);

    @Resource
    private RestTemplate restTemplate;

    @HystrixCommand(fallbackMethod = "getUserServiceFallback")
    public String getUserService(Long uid) {
        return restTemplate.getForEntity("http://USER-SERVICE/user?uid=" + uid, String.class).getBody();
    }

    private String getUserServiceFallback(Long uid) {
        return "error";
    }

    @HystrixCollapser(batchMethod = "getAllUser",
            collapserProperties = {@HystrixProperty(name = "timerDelayInMilliseconds", value = "500")})
    public String getUser(Long uid) {
        return null;
    }

    @HystrixCommand(fallbackMethod = "getAllUserFallback")
    public List<String> getAllUser(List<Long> uids) {
        LOGGER.info("getAllUser()");
        return restTemplate.getForEntity("http://USER-SERVICE/user?uids={1}", List.class, StringUtils.join(uids, ",")).getBody();
    }

    private List<String> getAllUserFallback(List<Long> uids) {
        return new ArrayList<>();
    }

}
